package service

import (
	"gogame/logger"
	"sync"
)

const (
	Stop     = 0
	Running  = 1
	Starting = 2
	Stopping = 3
)

type IService interface {
	Wait(wg *sync.WaitGroup) // 等待服务结束

	Start(svr any) // 开启服务
	Stop(svr any)  // 停止服务
	Status() int   // 服务状态

	SetName(string)  // 设置服务名
	GetName() string // 获取服务名

	SetListen(string)  // 设置监听地址
	GetListen() string // 获取监听地址

	SetTag(string)  // 设置别名
	GetTag() string // 获取别名

	Notice(svr any, data ...any) // 服务通知
}

type IServiceNotice interface {
	HandleNotice(data []any) // 处理服务通知
}

type IServiceStartStopServer interface {
	StartServer(serviceName, listen string) // 服务开启
	StopServer()                            // 实际停止服务方法
}

type Service struct {
	stat   int
	name   string
	listen string
	tag    string

	closeChan chan struct{}
}

func (s *Service) Status() int {
	return s.stat
}

func (s *Service) Wait(wg *sync.WaitGroup) {
	<-s.closeChan
	logger.Print("service【%s】close!", s.name)
	wg.Done()

}

func (s *Service) Start(svr any) {
	s.closeChan = make(chan struct{})
	if s.stat != Stop {
		return
	}

	s.stat = Starting
	svr.(IServiceStartStopServer).StartServer(s.name, s.listen)
	s.stat = Running
	logger.Print("service【%s】 start success!\n", s.name)

}

func (s *Service) Stop(svr any) {
	s.stat = Stopping
	svr.(IServiceStartStopServer).StopServer()
	s.closeChan <- struct{}{}

}

func (s *Service) GetName() string {
	return s.name
}

func (s *Service) SetName(serviceName string) {
	if s.name == "" {
		s.name = serviceName
	}
}

func (s *Service) GetListen() string {
	return s.listen
}

func (s *Service) SetListen(listen string) {
	if s.listen == "" {
		s.listen = listen
	}
}

func (s *Service) GetTag() string {
	return s.tag
}

func (s *Service) SetTag(tag string) {
	if s.tag == "" {
		s.tag = tag
	}
}

func (s *Service) Notice(svr any, data ...any) {
	svr.(IServiceNotice).HandleNotice(data)

}
